package com.ddm.service.impl.webImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ddm.entity.Bookmark;
import com.ddm.mapper.BookmarkMapper;
import com.ddm.service.webService.BookmarkService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

// 在 Service 层中调用
@Slf4j
@Service
public class BookmarkServiceImpl extends ServiceImpl<BookmarkMapper, Bookmark> implements BookmarkService{

    @Autowired
    private BookmarkMapper bookmarkMapper;

    /**
     * 添加收藏记录
     * @param bookmark 收藏实体（包含 user_id、course_id/regulation_id 等字段）
     * @return 是否添加成功（1：成功，0：失败）
     */
    @Override
    @Transactional
    public int addBookmark(Bookmark bookmark) {
        // 1. 参数校验
        if (bookmark.getUserId() == null) {
            throw new RuntimeException("用户ID不能为空");
        }

        // 2. 动态构建查询条件（检查是否已收藏）
        LambdaQueryWrapper<Bookmark> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Bookmark::getUserId, bookmark.getUserId());

        // 根据哪个ID字段非空，决定检查哪个类型
        if (bookmark.getStandardId() != null) {
            queryWrapper.eq(Bookmark::getStandardId, bookmark.getStandardId());
        } else if (bookmark.getMarket_id() != null) {
            queryWrapper.eq(Bookmark::getMarket_id, bookmark.getMarket_id());
        } else if (bookmark.getRegulation_id() != null) {
            queryWrapper.eq(Bookmark::getRegulation_id, bookmark.getRegulation_id());
        } else if (bookmark.getCourse_id() != null) {
            queryWrapper.eq(Bookmark::getCourse_id, bookmark.getCourse_id());
        } else if (bookmark.getExam_id() != null) {
            queryWrapper.eq(Bookmark::getExam_id, bookmark.getExam_id());
        }else if (bookmark.getSupplyId() != null) {
            queryWrapper.eq(Bookmark::getSupplyId, bookmark.getSupplyId());
        }
        else {
            throw new RuntimeException("至少需要指定一个收藏内容的ID");
        }

        // 3. 检查是否已存在
        if (bookmarkMapper.selectCount(queryWrapper) > 0) {
            throw new RuntimeException("该内容已收藏，请勿重复添加");
        }

        // 4. 插入新记录
        return bookmarkMapper.insert(bookmark);
    }

    /**
     * 删除收藏记录
     * @param bookmark 收藏实体（包含 user_id、course_id/regulation_id 等字段）
     * @return 是否删除成功（true：成功，false：失败）
     */
    @Override
    @Transactional
    public boolean deleteBookmark(Bookmark bookmark) {
        if (bookmark.getUserId() == null) {
            throw new RuntimeException("用户ID不能为空");
        }

        // 构建删除条件
        LambdaQueryWrapper<Bookmark> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Bookmark::getUserId, bookmark.getUserId());

        if (bookmark.getStandardId() != null) {
            wrapper.eq(Bookmark::getStandardId, bookmark.getStandardId());
        } else if (bookmark.getCourse_id() != null) {
            wrapper.eq(Bookmark::getCourse_id, bookmark.getCourse_id());
        } else if (bookmark.getMarket_id() != null) {
            wrapper.eq(Bookmark::getMarket_id, bookmark.getMarket_id());
        } else if (bookmark.getRegulation_id() != null) {
            wrapper.eq(Bookmark::getRegulation_id, bookmark.getRegulation_id());
        }else if (bookmark.getExam_id() != null) {
            wrapper.eq(Bookmark::getExam_id, bookmark.getExam_id());
        }else if (bookmark.getSupplyId() != null) {
            wrapper.eq(Bookmark::getSupplyId, bookmark.getSupplyId());
        }
        else {
            throw new RuntimeException("至少需要指定一个收藏内容的ID");
        }

        // 1. 删除前检查记录是否存在
        int countBefore = bookmarkMapper.selectCount(wrapper);
        if (countBefore == 0) {
            throw new RuntimeException("该内容未收藏，无需删除"); // 提前抛异常，避免无效操作
        }

        // 2. 执行删除
        bookmarkMapper.delete(wrapper);

        // 3. 删除后检查是否成功（记录数应为0）
        int countAfter = bookmarkMapper.selectCount(wrapper);
        return countAfter == 0; // 只有删除后记录数为0，才返回true（成功）
    }

    /**
     * 检查是否已收藏
     * @param bookmark 包含userId和具体资源ID（如standardId/market_id等）
     * @return true：已收藏，false：未收藏
     */
    @Override
    public boolean checkBookmark(Bookmark bookmark) {
        // 1. 参数校验
        if (bookmark.getUserId() == null) {
            throw new RuntimeException("用户ID不能为空");
        }

        // 2. 动态构建构建查询条件
        LambdaQueryWrapper<Bookmark> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Bookmark::getUserId, bookmark.getUserId());

        // 根据非空ID字段动态添加条件
        if (bookmark.getStandardId() != null) {
            queryWrapper.eq(Bookmark::getStandardId, bookmark.getStandardId());
        } else if (bookmark.getMarket_id() != null) {
            queryWrapper.eq(Bookmark::getMarket_id, bookmark.getMarket_id());
        } else if (bookmark.getRegulation_id() != null) {
            queryWrapper.eq(Bookmark::getRegulation_id, bookmark.getRegulation_id());
        } else if (bookmark.getCourse_id() != null) {
            queryWrapper.eq(Bookmark::getCourse_id, bookmark.getCourse_id());
        }else if (bookmark.getExam_id() != null) {
            queryWrapper.eq(Bookmark::getExam_id, bookmark.getExam_id());
        }else if (bookmark.getSupplyId() != null) {
            queryWrapper.eq(Bookmark::getSupplyId, bookmark.getSupplyId());
        }
        else {
            throw new RuntimeException("至少需要指定指定一个收藏内容的ID");
        }

        // 3. 查询是否存在记录
        return bookmarkMapper.selectCount(queryWrapper) > 0;
    }

    /**
     * 检查用户是否已报名竞赛
     * @param userId 用户ID
     * @param examId 竞赛ID
     * @return 是否已报名
     */
    @Override
    public boolean checkExamRegistration(Long userId, Long examId) {
        if (userId == null || examId == null) {
            return false;
        }

        LambdaQueryWrapper<Bookmark> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Bookmark::getUserId, userId)
                   .eq(Bookmark::getExam_id, examId);

        return bookmarkMapper.selectCount(queryWrapper) > 0;
    }

    /**
     * 获取用户报名的竞赛ID列表
     * @param userId 用户ID
     * @return 竞赛ID列表
     */
    @Override
    public List<Long> getRegisteredExamIds(Long userId) {
        if (userId == null) {
            return new ArrayList<>();
        }

        return bookmarkMapper.selectExamIdsByUserId(userId);
    }

    /**
     * 获取用户收藏的供求信息ID列表
     *
     * @param userId 用户ID
     * @return 供求信息ID列表
     */
    @Override
    public List<Bookmark> getCollectedSupplyIds(Long userId) {
        if (userId == null) {
            log.warn("获取收藏供求信息失败：用户ID为空");
            return new ArrayList<>();
        }

        // 构建查询条件：过滤 supply_id 非空的记录
        LambdaQueryWrapper<Bookmark> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Bookmark::getUserId, userId)
                .isNotNull(Bookmark::getSupplyId);

        // 查询 Bookmark 列表（此时 supply_id 已能正确注入 Integer 值）
        List<Bookmark> bookmarks = baseMapper.selectList(queryWrapper);
        log.info("查询到的 Bookmark 列表：{}", bookmarks); // 验证 supply_id 是否为 1/5

////        // 提取 supply_id 并转为 Long（匹配方法返回值类型）
////        List<Long> supplyIds = bookmarks.stream()
////                .filter(bookmark -> bookmark != null) // 过滤 null 对象
////                .map(Bookmark::getSupplyId)          // 提取supply_id
////                .filter(Objects::nonNull)             // 双重保险（已被 queryWrapper 过滤）
////                .distinct()                           // 去重
////                .collect(Collectors.toList());
//
//        log.info("用户[{}]收藏的供求ID列表：{}，共{}条", userId, supplyIds, supplyIds.size());
//        return supplyIds;
        return bookmarks;
    }
}